package cn.com.bluemoon.daps.notice.infrastructure.service.impl;


import cn.com.bluemoon.daps.notice.core.PreSendMsgInfo;
import cn.com.bluemoon.daps.notice.infrastructure.DapMailServiceFacade;
import cn.com.bluemoon.daps.notice.infrastructure.entity.DapSendMailRecord;
import cn.com.bluemoon.daps.notice.infrastructure.mapper.DapSendMailRecordMapper;
import cn.com.bluemoon.daps.notice.infrastructure.service.DapSendMailRecordService;
import cn.com.bluemoon.daps.notice.template.CustomFreemarkerTemplate;
import cn.com.bluemoon.daps.notice.template.MetadataImpactMessage;
import cn.com.bluemoon.daps.notice.template.base.BaseMessage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * <p>
 * 邮件发送记录表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-06-15
 */
@Slf4j
@Service
public class DapSendMailRecordServiceImpl extends ServiceImpl<DapSendMailRecordMapper, DapSendMailRecord>
        implements DapSendMailRecordService {

    @Autowired
    private DapMailServiceFacade mailService;

    @Override
    public boolean send(BaseMessage baseMsg) {
        return send0(baseMsg);
    }

    @Override
    public boolean send(DapSendMailRecord errorRecord) {
        return mailService.sendHtmlMailAtt(errorRecord.getAddressees().toArray(new String[0]), null, null,
                errorRecord.getMailTheme(), errorRecord.getSendContent(), Maps.newHashMap());
    }

    @Override
    public PreSendMsgInfo preSend(BaseMessage baseMsg) {
        CustomFreemarkerTemplate template = getCustomFreemarkerTemplate(baseMsg);
        return new PreSendMsgInfo(template.getTemplateContent(), template.getTemplateMsg());
    }


    /**
     * 发送邮件，最多尝试5次
     *
     * @param baseMsg x
     * @return true 成功 false失败
     */
    private boolean send0(BaseMessage baseMsg) {
        CustomFreemarkerTemplate template = getCustomFreemarkerTemplate(baseMsg);
        String content = template.getTemplateContent();
        BaseMessage templateMsg = template.getTemplateMsg();
        int tryTime = 5;
        boolean isOk = false;
        while (!isOk && tryTime-- >= 0) {
            isOk = mailService.sendHtmlMailAtt(templateMsg.getRcs().toArray(new String[0]),
                    templateMsg.getCcs().toArray(new String[0]), templateMsg.getBcc().toArray(new String[0]),
                    templateMsg.getTopic(), content, templateMsg.getAttachmentMap());
        }
        log.info("发送消息，status：{}，try time: {}, content:{}", isOk, tryTime, content);
        // 持久化
        DapSendMailRecord record = new DapSendMailRecord();
        record.setAddressees(new ArrayList<>(templateMsg.getRcs()));
        record.setMailTheme(templateMsg.getTopic());
        record.setReasonDescription(templateMsg.getAction());
        record.setSender(templateMsg.getSender());
        record.setSendContent(content);
        record.setSendStatus(isOk);
        if (StringUtils.isNotBlank(baseMsg.getMsgRecordId())){
            record.setId(baseMsg.getMsgRecordId());
        }
        boolean status = save(record);
        log.info("消息结果持久化情况,id={}，status：{}", record.getId(), status);
        return isOk;
    }

    private CustomFreemarkerTemplate getCustomFreemarkerTemplate(BaseMessage baseMsg) {
        CustomFreemarkerTemplate template = new CustomFreemarkerTemplate(baseMsg);
        template.setValidateTemplateMsg(true);
        return template;
    }

}
